import axios from "axios";
import { getToken, removerUserInfo } from "./user";
import { showFailToast } from 'vant';
import router from "@/router";
axios.defaults.baseURL = import.meta.env.VITE_BASE_URL;
axios.defaults.timeout = 8000;
axios.defaults.headers['content-type'] = 'application/x-www-form-urlencoded'

// 添加拦截器
axios.interceptors.request.use(function(config){
  if (getToken()) {
    if (config.method === 'get' || config.method === 'delete') {
      config.params = {
        ...config.params,
        token: getToken()
      }
    } else {
      config.data = {
        ...config.data,
        token: getToken()
      }
    }
  }
  return config
},function(error){
  Promise.reject(error)
})
// 添加响应拦截器
axios.interceptors.response.use(function(res){
  // 2000 token过期或者未登录
  switch (res.data.code) {
    case 2000:
      removerUserInfo();
      showFailToast({
        message: '登录过期或未登录',
        duration: 2000,
        onClose: () => {
          // 去登录页
          router.replace('/login')
        }
      }) 
      break;
    default:
      break;
  
  }
  return res
}, function(error){
  Promise.reject(error)
})

export default axios